﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Library.AppWeb
{
    public class Cryptography
    {
        private static byte[] bSalt = new byte[] { 80, 0x76, 0x61, 110, 0x21, 0x4d, 0x65, 100, 0x76, 0x15, 100, 0x65, 0x76 };

        public static string AesDecryptString(string strSource, string strPassword)
        {
            strPassword = strPassword + "1213ckjkvivaLaLa";
            strPassword = strPassword.Substring(0, 0x10);
            using (AesCryptoServiceProvider provider = GetProvider(Encoding.Default.GetBytes(strPassword)))
            {
                byte[] buffer = Convert.FromBase64String(strSource);
                ICryptoTransform transform = provider.CreateDecryptor();
                MemoryStream stream = new MemoryStream(buffer, 0, buffer.Length);
                CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read);
                return new StreamReader(stream2).ReadToEnd();
            }
        }

        public static string AesEncryptString(string strSource, string strPassword)
        {
            strPassword = strPassword + "1213ckjkvivaLaLa";
            strPassword = strPassword.Substring(0, 0x10);
            using (AesCryptoServiceProvider provider = GetProvider(Encoding.Default.GetBytes(strPassword)))
            {
                byte[] bytes = Encoding.ASCII.GetBytes(strSource);
                ICryptoTransform transform = provider.CreateEncryptor();
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                return Convert.ToBase64String(stream.ToArray());
            }
        }

        public static string Decrypt(string strText, string strEncrKey)
        {
            if (strEncrKey.Trim().Length < 9)
            {
                strEncrKey = "68686782349fs@#$%f23" + strEncrKey;
            }
            byte[] rgbKey = new byte[8];
            byte[] rgbIV = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
            try
            {
                byte[] buffer3;
                int length = 8;
                if (strEncrKey.Length < 8)
                {
                    length = strEncrKey.Length;
                }
                rgbKey = Encoding.UTF8.GetBytes(strEncrKey.Substring((strEncrKey.Length - length) - 1, length));
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                buffer3 = buffer3 = Convert.FromBase64String(strText);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                stream2.Write(buffer3, 0, buffer3.Length);
                stream2.FlushFinalBlock();
                return Encoding.UTF8.GetString(stream.ToArray());
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static void Decrypt(string fileIn, string fileOut, string Password)
        {
            int num2;
            FileStream stream = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream stream2 = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 110, 0x20, 0x4d, 0x65, 100, 0x76, 0x65, 100, 0x65, 0x76 });
            Rijndael rijndael = Rijndael.Create();
            rijndael.Key = bytes.GetBytes(0x20);
            rijndael.IV = bytes.GetBytes(0x10);
            CryptoStream stream3 = new CryptoStream(stream2, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
            int count = 0x1000;
            byte[] buffer = new byte[count];
            do
            {
                num2 = stream.Read(buffer, 0, count);
                stream3.Write(buffer, 0, num2);
            }
            while (num2 != 0);
            stream3.Close();
            stream.Close();
        }

        public static string DecryptRijinDael(string cipherText, string Password)
        {
            byte[] cipherData = Convert.FromBase64String(cipherText);
            PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, bSalt);
            byte[] buffer2 = DecryptRijinDael(cipherData, bytes.GetBytes(0x20), bytes.GetBytes(0x10));
            return Encoding.Unicode.GetString(buffer2);
        }

        public static byte[] DecryptRijinDael(byte[] cipherData, byte[] Key, byte[] IV)
        {
            MemoryStream stream = new MemoryStream();
            Rijndael rijndael = Rijndael.Create();
            rijndael.Key = Key;
            rijndael.IV = IV;
            CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
            stream2.Write(cipherData, 0, cipherData.Length);
            stream2.Close();
            return stream.ToArray();
        }

        public static void DecryptRijinDael(string fileIn, string fileOut, string Password)
        {
            int num2;
            FileStream stream = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream stream2 = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, bSalt);
            Rijndael rijndael = Rijndael.Create();
            rijndael.Key = bytes.GetBytes(0x20);
            rijndael.IV = bytes.GetBytes(0x10);
            CryptoStream stream3 = new CryptoStream(stream2, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
            int count = 0x1000;
            byte[] buffer = new byte[count];
            do
            {
                num2 = stream.Read(buffer, 0, count);
                stream3.Write(buffer, 0, num2);
            }
            while (num2 != 0);
            stream3.Close();
            stream.Close();
        }

        public static string DecryptTextFromFileRijinDael(string FileName, string Password)
        {
            try
            {
                FileStream stream = File.Open(FileName, FileMode.OpenOrCreate);
                Rijndael rijndael = Rijndael.Create();
                PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, bSalt);
                CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateDecryptor(bytes.GetBytes(0x20), bytes.GetBytes(0x10)), CryptoStreamMode.Read);
                StreamReader reader = new StreamReader(stream2);
                string str = null;
                try
                {
                    str = reader.ReadLine();
                }
                catch (Exception exception)
                {
                    Console.WriteLine("An error occurred: {0}", exception.Message);
                }
                finally
                {
                    reader.Close();
                    stream2.Close();
                    stream.Close();
                }
                return str;
            }
            catch (CryptographicException exception2)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", exception2.Message);
                return null;
            }
            catch (UnauthorizedAccessException exception3)
            {
                Console.WriteLine("A file error occurred: {0}", exception3.Message);
                return null;
            }
        }

        public static string Encrypt(string strText, string strEncrKey)
        {
            if (strEncrKey.Trim().Length < 9)
            {
                strEncrKey = "68686782349fs@#$%f23" + strEncrKey;
            }
            byte[] rgbKey = new byte[8];
            byte[] rgbIV = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
            try
            {
                int length = 8;
                if (strEncrKey.Length < 8)
                {
                    length = strEncrKey.Length;
                }
                rgbKey = Encoding.UTF8.GetBytes(strEncrKey.Substring((strEncrKey.Length - length) - 1, length));
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                byte[] bytes = Encoding.UTF8.GetBytes(strText);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                return Convert.ToBase64String(stream.ToArray());
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static void Encrypt(string fileIn, string fileOut, string Password)
        {
            int num2;
            FileStream stream = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream stream2 = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 110, 0x20, 0x4d, 0x65, 100, 0x76, 0x65, 100, 0x65, 0x76 });
            Rijndael rijndael = Rijndael.Create();
            rijndael.Key = bytes.GetBytes(0x20);
            rijndael.IV = bytes.GetBytes(0x10);
            CryptoStream stream3 = new CryptoStream(stream2, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            int count = 0x1000;
            byte[] buffer = new byte[count];
            do
            {
                num2 = stream.Read(buffer, 0, count);
                stream3.Write(buffer, 0, num2);
            }
            while (num2 != 0);
            stream3.Close();
            stream.Close();
        }

        public static string EncryptRijinDael(string clearText, string Password)
        {
            byte[] clearData = Encoding.Unicode.GetBytes(clearText);
            PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, bSalt);
            return Convert.ToBase64String(EncryptRijinDael(clearData, bytes.GetBytes(0x20), bytes.GetBytes(0x10)));
        }

        public static void EncryptRijinDael(string fileIn, string fileOut, string Password)
        {
            int num2;
            FileStream stream = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
            FileStream stream2 = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
            PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, bSalt);
            Rijndael rijndael = Rijndael.Create();
            rijndael.Key = bytes.GetBytes(0x20);
            rijndael.IV = bytes.GetBytes(0x10);
            CryptoStream stream3 = new CryptoStream(stream2, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            int count = 0x1000;
            byte[] buffer = new byte[count];
            do
            {
                num2 = stream.Read(buffer, 0, count);
                stream3.Write(buffer, 0, num2);
            }
            while (num2 != 0);
            stream3.Close();
            stream.Close();
        }

        public static byte[] EncryptRijinDael(byte[] clearData, byte[] Key, byte[] IV)
        {
            MemoryStream stream = new MemoryStream();
            Rijndael rijndael = Rijndael.Create();
            rijndael.Key = Key;
            rijndael.IV = IV;
            CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(clearData, 0, clearData.Length);
            stream2.Close();
            return stream.ToArray();
        }

        public static void EncryptTextToFileRijinDael(string Data, string FileName, string Password)
        {
            try
            {
                FileStream stream = File.Open(FileName, FileMode.OpenOrCreate);
                Rijndael rijndael = Rijndael.Create();
                PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, bSalt);
                CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateEncryptor(bytes.GetBytes(0x20), bytes.GetBytes(0x10)), CryptoStreamMode.Write);
                StreamWriter writer = new StreamWriter(stream2);
                try
                {
                    writer.WriteLine(Data);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("An error occurred: {0}", exception.Message);
                }
                finally
                {
                    writer.Close();
                    stream2.Close();
                    stream.Close();
                }
            }
            catch (CryptographicException exception2)
            {
                Console.WriteLine("A Cryptographic error occurred: {0}", exception2.Message);
            }
            catch (UnauthorizedAccessException exception3)
            {
                Console.WriteLine("A file error occurred: {0}", exception3.Message);
            }
        }

        private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
        {
            byte[] buffer = suggestedKey;
            List<byte> list = new List<byte>();
            for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8)
            {
                list.Add(buffer[(i / 8) % buffer.Length]);
            }
            return list.ToArray();
        }

        private static AesCryptoServiceProvider GetProvider(byte[] key)
        {
            AesCryptoServiceProvider p = new AesCryptoServiceProvider();
            p.BlockSize = 0x80;
            p.KeySize = 0x80;
            p.Mode = CipherMode.CBC;
            p.Padding = PaddingMode.PKCS7;
            p.GenerateIV();
            p.IV = new byte[0x10];
            byte[] buffer = GetKey(key, p);
            p.Key = buffer;
            return p;
        }

        public static string HashingMD5(string strSource)
        {
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            byte[] bytes = Encoding.UTF8.GetBytes(strSource);
            bytes = provider.ComputeHash(bytes);
            StringBuilder builder = new StringBuilder();
            foreach (byte num in bytes)
            {
                builder.Append(num.ToString("x2").ToLower());
            }
            return builder.ToString();
        }

        public static string HashingSHA512(string strSource)
        {
            SHA512 sha = new SHA512Managed();
            byte[] bytes = Encoding.UTF8.GetBytes(strSource);
            bytes = sha.ComputeHash(bytes);
            StringBuilder builder = new StringBuilder();
            foreach (byte num in bytes)
            {
                builder.Append(num.ToString("x2").ToLower());
            }
            return builder.ToString();
        }

        public static string RSADecrypt(string strInputString, int dwKeySize, string strKey)
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(dwKeySize);
            provider.FromXmlString(strKey);
            int length = (((dwKeySize / 8) % 3) != 0) ? ((((dwKeySize / 8) / 3) * 4) + 4) : (((dwKeySize / 8) / 3) * 4);
            int num2 = strInputString.Length / length;
            ArrayList list = new ArrayList();
            for (int i = 0; i < num2; i++)
            {
                byte[] array = Convert.FromBase64String(strInputString.Substring(length * i, length));
                Array.Reverse(array);
                list.AddRange(provider.Decrypt(array, true));
            }
            return Encoding.UTF32.GetString(list.ToArray(Type.GetType("System.Byte")) as byte[]);
        }

        public static string RSAEncrypt(string strInputString, int dwKeySize, string strKey)
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(dwKeySize);
            provider.FromXmlString(strKey);
            int num = dwKeySize / 8;
            byte[] bytes = Encoding.UTF32.GetBytes(strInputString);
            int num2 = num - 0x2a;
            int length = bytes.Length;
            int num4 = length / num2;
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i <= num4; i++)
            {
                byte[] dst = new byte[((length - (num2 * i)) > num2) ? num2 : (length - (num2 * i))];
                Buffer.BlockCopy(bytes, num2 * i, dst, 0, dst.Length);
                byte[] array = provider.Encrypt(dst, true);
                Array.Reverse(array);
                builder.Append(Convert.ToBase64String(array));
            }
            return builder.ToString();
        }

        public static string RSASignString(string strKey, string strDataToSign)
        {
            try
            {
                CspParameters parameters = new CspParameters();
                parameters.Flags = CspProviderFlags.UseMachineKeyStore;
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider(0x400, parameters);
                provider.FromXmlString(strKey);
                byte[] bytes = new ASCIIEncoding().GetBytes(strDataToSign);
                return Convert.ToBase64String(provider.SignData(bytes, "SHA"));
            }
            catch
            {
                return "";
            }
        }

        public static bool RSAVerifySign(string strKey, string strSignData, string strDataToVeriSign)
        {
            try
            {
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.FromXmlString(strKey);
                byte[] bytes = new ASCIIEncoding().GetBytes(strDataToVeriSign);
                byte[] signature = Convert.FromBase64String(strSignData);
                return provider.VerifyData(bytes, "SHA", signature);
            }
            catch
            {
                return false;
            }
        }

    }
}
